package com.shyroke.daydayzhuanjob;

import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuansvc.service.ISpiderService;
import com.shyroke.daydayzhuansvc.service.ISysDownService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 类名 ：爬虫相关定时任务，用于爬取其他网站数据
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/2/20 13:49
 */
@Component
public class SpiderJob {

    @Autowired
    private ISpiderService spiderService;
    @Autowired
    private ISysDownService sysDownService;
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private RedisTemplate redisTemplate;


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 爬取目标网站的数据
     */
    @Scheduled(initialDelay=40*60*1000,fixedRate=40*60*1000)
    public void spider()  {
        //如果是开发模式，则不进行301重定向跳转到www.daydayzhuan.com网站
        if("dev".equals(active)){
            return;
        }
        logger.info("==========爬虫定时任务开始==========");
        spiderService.spider(null);
        logger.info("==========爬虫定时任务结束==========");
    }

    /**
     * 每天12点清空当天下载量
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearCount()  {
        logger.info("=====每天12点清空当天下载量开始=====");
        sysDownService.clearCount();
        //删除今日可赚
        Object profitTodayObj = redisTemplate.opsForValue().get(RedisKeyPrefix.PROFIT_TODAY);
        if(profitTodayObj != null){
            BigDecimal profitToday = (BigDecimal)profitTodayObj;
            if(BigDecimal.ZERO.compareTo(profitToday) != 0){
                Object profitAllObj = redisTemplate.opsForValue().get(RedisKeyPrefix.PROFIT_All);
                BigDecimal all = (profitAllObj == null)?new BigDecimal(0):(BigDecimal)profitAllObj;
                BigDecimal sum = all.add(profitToday);
                redisTemplate.opsForValue().set(RedisKeyPrefix.PROFIT_All,sum);
            }
        }
        redisTemplate.delete(RedisKeyPrefix.PROFIT_TODAY);
        //删除标签缓存
        redisTemplate.delete(RedisKeyPrefix.HOTKEY);
        logger.info("=====每天12点清空当天下载量结束=====");
    }

}
